package org.summerframework.core.util;

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.method.HandlerMethod;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author 石超
 * @version v1.0.0
 */
public class AnnotationUtils extends org.springframework.core.annotation.AnnotationUtils {

    public static <A extends Annotation> A findAnnotation(HandlerMethod handlerMethod, Class<A> aClass) {
        if (handlerMethod == null) {
            return null;
        }
        return findAnnotation(handlerMethod.getBeanType(), handlerMethod.getMethod(), aClass);
    }

    public static <A extends Annotation> A findAnnotation(HandlerMethod handlerMethod, List<Class<A>> classList) {
        for (Class<A> aClass : classList) {
            A annotation = findAnnotation(handlerMethod, aClass);

            if (annotation != null) {
                return annotation;
            }
        }

        return null;
    }

    public static boolean hasAnnotation(HandlerMethod handlerMethod, List<Class<? extends Annotation>> classList) {
        if (handlerMethod == null) {
            return false;
        }

        for (Class<? extends Annotation> aClass : classList) {
            Annotation annotation = findAnnotation(handlerMethod, aClass);

            if (annotation != null) {
                return true;
            }
        }

        return false;
    }

    public static boolean hasAnnotation(HandlerMethod handlerMethod, Class<? extends Annotation> aClass) {
        return findAnnotation(handlerMethod, aClass) != null;
    }

    public static <A extends Annotation> A findAnnotation(Class<?> c, Method method, Class<A> aClass) {
        A a = AnnotatedElementUtils.findMergedAnnotation(method, aClass);

        if (a == null) {
            return AnnotatedElementUtils.findMergedAnnotation(c, aClass);
        }

        return a;
    }
}
